﻿using Microsoft.AspNetCore.Http;
using System.Net;
using System;
using Newtonsoft.Json;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using MS.Core.Helper;
using MS.Core.Model;


namespace MS.Core.Middleware
{
    /// <summary>
    /// 统一异常处理
    /// </summary>
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;  // 用来处理上下文请求  
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext); //要么在中间件中处理，要么被传递到下一个中间件中去
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理
            }
        }
        /// <summary>
        /// 捕获异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";  // 返回json 类型
            NLogHelper.GetLog().Error(exception);
            Rt RtModel = Rt.Error(exception.ToString());
            var result = JsonConvert.SerializeObject(RtModel);
            await context.Response.WriteAsync(result);
            //var response = context.Response;
            // 自定义的异常错误信息类型
            //switch (exception)
            //{ 
            //    case ApplicationException ex:
            //    if (ex.Message.Contains("Invalid token"))
            //    {
            //        response.StatusCode = (int)HttpStatusCode.Forbidden;
            //        break;
            //    }
            //    break;
            //default:
            //    break;
            //}
        }
    }
}
